package com.dorm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dorm.common.PageResult;
import com.dorm.common.Result;
import com.dorm.entity.Notice;
import com.dorm.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 公告控制器
 */
@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result<PageResult<Notice>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer status) {
        
        Page<Notice> page = noticeService.pageQuery(pageNum, pageSize, title, type, status);
        PageResult<Notice> result = new PageResult<>(
                page.getRecords(),
                page.getTotal(),
                page.getCurrent(),
                page.getSize()
        );
        return Result.success(result);
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public Result<Notice> getById(@PathVariable Long id) {
        Notice notice = noticeService.getById(id);
        // 增加浏览次数
        if (notice != null) {
            notice.setViewCount(notice.getViewCount() == null ? 1 : notice.getViewCount() + 1);
            noticeService.updateById(notice);
        }
        return Result.success(notice);
    }

    /**
     * 新增
     */
    @PostMapping
    public Result<String> add(@RequestBody Notice notice, @RequestAttribute Long userId) {
        notice.setPublisherId(userId);
        notice.setViewCount(0);
        noticeService.save(notice);
        return Result.success("添加成功");
    }

    /**
     * 修改
     */
    @PutMapping
    public Result<String> update(@RequestBody Notice notice) {
        noticeService.updateById(notice);
        return Result.success("修改成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        noticeService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     * 发布
     */
    @PostMapping("/publish/{id}")
    public Result<String> publish(@PathVariable Long id) {
        Notice notice = noticeService.getById(id);
        notice.setStatus(1);
        noticeService.updateById(notice);
        return Result.success("发布成功");
    }
}

